package com.example.servlet.config;

import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
    // 在 servlet 应用中使用 spring security 参考 https://docs.springjava.cn/spring-security/reference/servlet/getting-started.html


    @Bean
    @SneakyThrows
    public SecurityFilterChain securityFilterChain(HttpSecurity http) {
        // @formatter:off
        http
                .cors(Customizer.withDefaults())
                // 请求放行配置
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/auth/**", "/auth/login/**").permitAll()
                        .anyRequest().authenticated()
                )
                // X509 证书登录配置
                .x509(Customizer.withDefaults())
                // 防止跨站请求伪造（CSRF）配置
                .csrf(Customizer.withDefaults())
                // HTTP 基本认证配置
                .httpBasic(Customizer.withDefaults())
                // 表单登录配置
                .formLogin((form) -> form
                        .loginPage("/auth/login")
                        .permitAll()
                )
                // 设置会话管理器配置
                .sessionManagement((session) -> session
                        .sessionConcurrency(concurrency -> concurrency.maximumSessions(1))
                )
                // 记住我配置
                .rememberMe((rememberMe) -> rememberMe.userDetailsService(userDetailsService()));
        // @formatter:on
        return http.build();
    }

    // 在内存中创建两个用户，一个是普通用户，一个则是管理员
    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.builder()
                .passwordEncoder(passwordEncoder()::encode)
                .username("user")
                .password("123456")
                .roles("USER")
                .build();
        UserDetails admin = User.builder()
                .passwordEncoder(passwordEncoder()::encode)
                .username("admin")
                .password("123456")
                .roles("ADMIN", "USER")
                .build();
        return new InMemoryUserDetailsManager(user, admin);
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

}


// servlet 应用配置 Spring Security 安全配置参考 https://docs.springjava.cn/spring-security/reference/servlet/getting-started.html